package com.zxy.main;

import java.util.Timer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;
import com.zxy.tcp.ClientThread;
import com.zxy.tcp.CustTimeTask;
import com.zxy.tcp.MqttHandler;
import com.zxy.tcp.SelfTimeTask;
import com.zxy.tcp.ServerThread;
import com.zxy.tcp.ServerThreadHttp;

public class ServerMain extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init() throws ServletException
	{
		super.init();
		System.out.println("CDIsys_v3 Main开始==>"+Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss"));
		try
		{
			Init_Page.Init_Load();
		}
		catch(Exception es)
		{
		}

		if(com.zxy.common.Com_Fun.flagSconnections())
		{
			// 是否启用http协议接口
			if(Com_Para.bThread == true)
			{
				ServerThreadHttp athttp = new ServerThreadHttp("","");
				athttp.start();
			}
			// 中转节点Node客户端
			if(Com_Para.If_Child_Device == 1)
			{
				ClientThread st = new ClientThread();
				st.start();
			}
			// 中转节点Node服务端
			if(Com_Para.If_Parent_Device == 1)
			{
				if(Com_Para.AccSocketPort.indexOf(";") == -1)
				{
					ServerThread at = new ServerThread(Com_Para.AccSocketPort,0);
					at.start();
				}
				else{
					int i = 0;
					for(String strNum : Com_Para.AccSocketPort.split(";")){
						ServerThread at = new ServerThread(strNum,i);
						at.start();
						i ++;
					}
				}
			}
			// MQTT服务端
			if(Com_Para.MQTT_host.indexOf("tcp") == 0)
			{
				MqttHandler mh = new MqttHandler();
				mh.run();
			}
			/**** Session计时和删除数据 ***/
			Timer time2 = new Timer("CD_selftime");
			SelfTimeTask sthreadT = new SelfTimeTask();
			time2.scheduleAtFixedRate(sthreadT,3000,30000);

			// 自定义定时器
			int iIndex = 0;
			for(String num: Com_Para.CustTimeTaskNum.split(";"))
			{
				// 默认24小时
				int iLoop = 86400000;
				try
				{
					iLoop = Integer.valueOf(num);
				}
				catch(Exception es)
				{
				}
				Timer CustTime = new Timer("CD_CustTime_" + num);
				CustTimeTask ctt = new CustTimeTask();
				ctt.REFLECT_IN_CLASS = Com_Para.CustTimeREFLECT_IN_CLASS.split(";").length > iIndex ? Com_Para.CustTimeREFLECT_IN_CLASS.split(";")[iIndex] : "";
				CustTime.scheduleAtFixedRate(ctt,5000,iLoop);
				iIndex++;
			}
		}
		// 设置全局变量
		super.getServletContext().setAttribute("ht_T_PARAM_VALUE",Com_Para.ht_T_PARAM_VALUE);
		super.getServletContext().setAttribute("ht_T_DB_CONFIG",Com_Para.ht_T_DB_CONFIG);
		System.out.println("CDIsys_v3 Main结束==>"+Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss"));
	}
}